package models

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 面向运维的k8s项目
type K8sProject struct {
	Model         // 不用每次写ID 和 createAt了
	Name   string `json:"name" validate:"required,min=1,max=200" gorm:"uniqueIndex:name_cluster;type:varchar(100);comment:项目英文集群名称，支持使用通配符*进行模糊搜索" `
	NameZh string `json:"nameZh" validate:"required,min=1,max=500" gorm:"uniqueIndex;type:varchar(100);comment:k8s中文集群名称，支持使用通配符*进行模糊搜索" `

	Cluster    string `json:"cluster" gorm:"uniqueIndex:name_cluster;type:varchar(100);comment:k8s英文集群名称，支持使用通配符*进行模糊搜索" `
	TreeNodeId uint   `json:"treeNodeId" gorm:"comment:绑定到哪个节点的 面向第三层级"`
	UserID     uint

	// 一对多关系 https://gorm.io/zh_CN/docs/has_many.html
	K8sApps        []K8sApp
	CreateUserName string     `json:"createUserName" gorm:"-"`
	NodePath       string     `json:"nodePath" gorm:"-"` // a.b.c.d
	Key            string     `json:"key" gorm:"-"`      //给前端表格
	StreeNodeObj   *StreeNode `json:"streeNodeObj" gorm:"-"`
}

func DeleteK8sProjectOneByInstanceId(iid string) error {

	return Db.Select(clause.Associations).Unscoped().Where("instance_id = ?", iid).Delete(&K8sProject{}).Error
}

func (obj *K8sProject) CreateOne() error {
	return Db.Create(obj).Error

}

func (obj *K8sProject) UpdateOne() error {
	return Db.Where("id = ?", obj.ID).Updates(obj).Error

}

func (obj *K8sProject) FillDefaultData() error {
	return nil
}

func (obj *K8sProject) DeleteOne() error {

	return Db.Select(clause.Associations).Unscoped().Delete(obj).Error

}

func GetK8sProjectAll() (objs []*K8sProject, err error) {
	err = Db.Find(&objs).Error
	return
}

func (obj *K8sProject) UpdateFlowNodes(nodes []FlowNode) error {

	return Db.Model(obj).Association("FlowNodes").Replace(nodes)

}

func (obj *K8sProject) FillFrontAllData() error {
	dbUser, _ := GetUserById(int(obj.UserID))
	if dbUser != nil {
		obj.CreateUserName = dbUser.Username
	}

	obj.Key = fmt.Sprintf("%d", obj.ID)
	//把 服务树节点对象查询出来
	dbNode, err := GetStreeNodeById(int(obj.TreeNodeId))
	if err != nil {
		return err
	}

	dbNode.FillFrontAllDataSimple()
	obj.StreeNodeObj = dbNode
	obj.NodePath = dbNode.NodePath
	return nil
}

func GetK8sProjectCount() int {
	var count int64
	Db.Table("K8sProjectes").Count(&count)
	return int(count)
}

func GetK8sProjectAllWithLimitOffset(limit, offset int) (objs []*K8sProject, err error) {
	err = Db.Preload("FlowNodes").Limit(limit).Offset(offset).Find(&objs).Error
	return
}

func GetK8sProjectByLevel(level int) (objs []*K8sProject, err error) {
	err = Db.Where("level = ?", level).Preload("OpsAdmins").Find(&objs).Error
	return
}

// select * from ecs where
func GetK8sProjectByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*K8sProject, err error) {
	err = Db.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

func GetK8sProjectByInstanceId(instanceId string) (*K8sProject, error) {

	var dbObj K8sProject
	err := Db.Where("instance_id = ?", instanceId).Preload("FlowNodes").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("K8sProject不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetK8sProjectById(id int) (*K8sProject, error) {

	var dbObj K8sProject
	err := Db.Where("id = ?", id).Preload("K8sApps").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("K8sProject不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}
